#!/usr/bin/python
import ConfigParser
import commands
import sys
import argparse

from keyring import Keyring
from serverdb import ServerDB

def main():
    name = "pyrdp"
    protocol = "rdp"
    server = "pyrdp"

    config = ConfigParser.ConfigParser()

    serverdb = ServerDB()
    
    keyring = Keyring(name, protocol)
    parser = argparse.ArgumentParser(description='Python Remote Desktop Manager')
    parser.add_argument('-a', '--add', nargs=2, help='Adds a new user to gnome keyring', metavar=('username', 'password'))
    parser.add_argument('-d', '--delete', nargs=1, help='Removes a user from gnome keyring', metavar=('username'))
    parser.add_argument('-c', '--config', nargs=1, help='Specifies the location of pyrdp.conf', metavar=('config_file'))
    parser.add_argument('-v', '--verify', nargs=1, help='Verfies if a user exists in gnome keyring', metavar=('username'))
    parser.add_argument('-n', '--new', nargs=3, help='Adds a new server to the server database', metavar=('hostname common_name username'))
    parser.add_argument('-r', '--remove', nargs=1, help='Removes a server from the server database', metavar=('hostname'))
    
    args = vars(parser.parse_args())
    if args["config"]:
        config.read(args["config"][0])
        serverdb.read_file(config.get("pyrdp", "serverdb"))
    else:
        config.read('etc/pyrdp.conf')
        serverdb.read_file(config.get("pyrdp", "serverdb"))
    
    if args["new"]:
        if keyring.get_credentials(server, args["new"][2]) != None:
            serverdb.add_server(args["new"][1], args["new"][0], args["new"][2])
            serverdb.write_file(config.get("pyrdp", "serverdb"))
            print "Server has been added."
        else:
            print "User is NOT found in our database"
            
    if args["remove"]:
        print "Not implemented yet"
        
    if args["add"]:
        keyring.set_credentials((args["add"][0], args["add"][1]), server)
        print args["add"][0] + " has been added."
    
    if args["delete"]:
        keyring.forget_credentials(args["delete"][0], server)
        print args["delete"][0] + " removed from user database"

    if args["verify"]:
        if keyring.has_credentials(server):
            for item in keyring.get_credentials_list(server):
                if item.attributes["user"] == args["verify"][0]:
                    print "User: " + item.attributes["user"] + " is found in our database."
                    sys.exit(0)
            print "User: " + args["verify"][0] + " is NOT found in our database."

if __name__ == '__main__':
    main()
        
